package com.LeeCode;

/**
 * 统计全为 1 的正方形子矩阵
 */

public class Code1277 {
    public static void main(String[] args) {
        int[][] matrix = {
                {0, 1, 1, 1},
                {1, 1, 1, 1},
                {0, 1, 1, 1}
        };
        System.out.println(new Code1277().countSquares(matrix));
    }

    public int countSquares(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[][] preSum = new int[m + 1][n + 1];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                preSum[i + 1][j + 1] = matrix[i][j] + preSum[i][j + 1] + preSum[i + 1][j] - preSum[i][j];
            }
        }
        int maxLen = Math.min(m, n);
        int ans = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                // 枚举右下角的点
                for (int len = 1; len <= maxLen; len++) {
                    int x = i - len + 1, y = j - len + 1;
                    if (x < 0 || y < 0) break;
                    int count = preSum[i + 1][j + 1] - preSum[x][j + 1] - preSum[i + 1][y] + preSum[x][y];
                    if (count == len * len) ans++;
                }
            }
        }
        return ans;
    }
}
